package com.llb666.shop.items.infrastructure.persistence;

import com.llb666.common.core.enums.YesOrNo;
import com.llb666.shop.items.domain.entity.ItemsImg;
import com.llb666.shop.items.domain.repository.ItemsImgRepository;
import com.llb666.shop.items.infrastructure.conver.ItemsImgCvt;
import com.llb666.shop.items.infrastructure.mapper.ItemsImgMapper;
import com.llb666.shop.items.infrastructure.po.ItemsImgPo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;

/**
 * 商品图片仓储层实现类.
 *
 * @author llb666
 */
@Repository
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class ItemsImgRepositoryImpl implements ItemsImgRepository {

    private final ItemsImgMapper itemsImgMapper;

    /**
     * 查询商品图片信息.
     *
     * @param itemId 商品ID
     * @return 商品图片信息
     */
    @Override
    public List<ItemsImg> queryItemsImgById(String itemId) {
        Example example = new Example(ItemsImgPo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("itemId", itemId);
        return ItemsImgCvt.INSTANCE.po2doList(itemsImgMapper.selectByExample(example));
    }

    /**
     * 根据商品id查询商品主图.
     *
     * @param itemId 商品id
     * @return 商品主图url
     */
    @Override
    public String queryItemMainImgById(String itemId) {
        ItemsImgPo itemsImg = new ItemsImgPo();
        itemsImg.setItemId(itemId);
        itemsImg.setIsMain(YesOrNo.YES.type);
        ItemsImg result = ItemsImgCvt.INSTANCE.po2do(itemsImgMapper.selectOne(itemsImg));
        return result != null ? result.getUrl() : "";
    }

    /**
     * 根据商品id 查询主图列表.
     *
     * @param itemIds 商品ID列表
     * @return 商品主图列表
     */
    @Override
    @Async("itemsServiceExecutor")
    public CompletableFuture<List<ItemsImg>> queryItemMainImgsItemsImgByIds(List<String> itemIds) {
        Example example = new Example(ItemsImgPo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("itemId", itemIds);
        List<ItemsImg> itemsImgs = ItemsImgCvt.INSTANCE.po2doList(itemsImgMapper.selectByExample(example));
        return CompletableFuture.completedFuture(itemsImgs);
    }

    /**
     * 根据商品id查询商品主图图片
     *
     * @param itemsIdSet 商品id列表
     * @return 商品图片列表信息.
     */
    @Override
    public List<ItemsImg> getImgUrlsByItemsIds(Set<String> itemsIdSet) {
        Example example = new Example(ItemsImgPo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("isMain", YesOrNo.YES.type);
        criteria.andIn("itemId", itemsIdSet);
        return ItemsImgCvt.INSTANCE.po2doList(itemsImgMapper.selectByExample(example));
    }
}
